/**
 * 评论路由模块
 * @author HalRui
 * @version 1.0.0
 * @description 定义评论相关的API接口，包括评论创建、查询、更新、删除、点赞、回复等功能
 * @date 2025年9月27日
 */

const express = require('express');
const router = express.Router();
const commentsAPI = require('../../libs/comments-api');
const STATUS_CODES = require('../../utils/status-codes');

// 测试路由
router.get('/test', (req, res) => {
    console.log('测试路由被访问');
    res.json({ message: '评论路由正常工作' });
});

// 简化的评论创建测试
router.post('/create-test', (req, res) => {
    console.log('收到简化评论创建请求:', req.body);
    res.json({
        code: 200,
        message: '简化评论创建成功',
        data: { commentId: 999, content: '测试评论' }
    });
});

// 创建评论
router.post('/create', async (req, res) => {
    console.log('收到评论创建请求:', req.body);
    try {
        const { userId, videoID, content, parentId, ip } = req.body;
        
        console.log('参数验证中...');
        if (!userId || !videoID || !content) {
            console.log('参数验证失败');
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '用户ID、视频ID和评论内容不能为空'
            });
        }
        
        console.log('开始创建评论...');
        const comment = await commentsAPI.createComment({
            userId: parseInt(userId),
            videoID: parseInt(videoID),
            content: content.trim(),
            parentId: parentId ? parseInt(parentId) : 0,
            ip: ip || req.ip
        });
        
        console.log('评论创建成功:', comment);
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '评论创建成功',
            data: comment
        });
    } catch (error) {
        console.error('创建评论失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR,
            message: error.message || '创建评论失败'
        });
    }
});

// 获取评论列表
router.get('/list/:videoID', async (req, res) => {
    try {
        const { videoID } = req.params;
        const { parentId = 0, page = 1, limit = 20, sortBy = 'createAt', sortOrder = 'desc' } = req.query;
        
        if (!videoID) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '视频ID不能为空'
            });
        }
        
        const result = await commentsAPI.getCommentList({
            videoID: parseInt(videoID),
            parentId: parseInt(parentId),
            page: parseInt(page),
            limit: parseInt(limit),
            sortBy,
            sortOrder
        });
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '获取评论列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取评论列表失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR,
            message: error.message || '获取评论列表失败'
        });
    }
});

// 获取评论详情
router.get('/detail/:commentId', async (req, res) => {
    try {
        const { commentId } = req.params;
        
        if (!commentId) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '评论ID不能为空'
            });
        }
        
        const comment = await commentsAPI.getCommentDetail(parseInt(commentId));
        
        if (!comment) {
            return res.status(404).json({
                code: STATUS_CODES.NOT_FOUND,
                message: '评论不存在'
            });
        }
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '获取评论详情成功',
            data: comment
        });
    } catch (error) {
        console.error('获取评论详情失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR,
            message: error.message || '获取评论详情失败'
        });
    }
});

// 更新评论
router.put('/update/:commentId', async (req, res) => {
    try {
        const { commentId } = req.params;
        const { userId, content } = req.body;
        
        if (!commentId || !userId || !content) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '评论ID、用户ID和评论内容不能为空'
            });
        }
        
        const comment = await commentsAPI.updateComment(
            parseInt(commentId),
            parseInt(userId),
            content.trim()
        );
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '更新评论成功',
            data: comment
        });
    } catch (error) {
        console.error('更新评论失败:', error);
        if (error.message === '评论不存在') {
            res.status(404).json({
                code: STATUS_CODES.NOT_FOUND,
                message: error.message
            });
        } else if (error.message === '无权限修改此评论') {
            res.status(403).json({
                code: STATUS_CODES.FORBIDDEN,
                message: error.message
            });
        } else {
            res.status(500).json({
                code: STATUS_CODES.SERVER_ERROR,
                message: error.message || '更新评论失败'
            });
        }
    }
});

// 删除评论
router.delete('/delete/:commentId', async (req, res) => {
    try {
        const { commentId } = req.params;
        const { userId } = req.body;
        
        if (!commentId || !userId) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '评论ID和用户ID不能为空'
            });
        }
        
        const result = await commentsAPI.deleteComment(
            parseInt(commentId),
            parseInt(userId)
        );
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '删除评论成功',
            data: result
        });
    } catch (error) {
        console.error('删除评论失败:', error);
        if (error.message === '评论不存在') {
            res.status(404).json({
                code: STATUS_CODES.NOT_FOUND,
                message: error.message
            });
        } else if (error.message === '无权限删除此评论') {
            res.status(403).json({
                code: STATUS_CODES.FORBIDDEN,
                message: error.message
            });
        } else {
            res.status(500).json({
                code: STATUS_CODES.SERVER_ERROR,
                message: error.message || '删除评论失败'
            });
        }
    }
});

// 点赞评论
router.post('/like/:commentId', async (req, res) => {
    try {
        const { commentId } = req.params;
        const { userId } = req.body;
        
        if (!commentId || !userId) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '评论ID和用户ID不能为空'
            });
        }
        
        const result = await commentsAPI.likeComment(
            parseInt(commentId),
            parseInt(userId)
        );
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '点赞成功',
            data: result
        });
    } catch (error) {
        console.error('点赞评论失败:', error);
        if (error.message === '评论不存在') {
            res.status(404).json({
                code: STATUS_CODES.NOT_FOUND,
                message: error.message
            });
        } else {
            res.status(500).json({
                code: STATUS_CODES.SERVER_ERROR,
                message: error.message || '点赞失败'
            });
        }
    }
});

// 点踩评论
router.post('/unlike/:commentId', async (req, res) => {
    try {
        const { commentId } = req.params;
        const { userId } = req.body;
        
        if (!commentId || !userId) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '评论ID和用户ID不能为空'
            });
        }
        
        const result = await commentsAPI.unlikeComment(
            parseInt(commentId),
            parseInt(userId)
        );
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '点踩成功',
            data: result
        });
    } catch (error) {
        console.error('点踩评论失败:', error);
        if (error.message === '评论不存在') {
            res.status(404).json({
                code: STATUS_CODES.NOT_FOUND,
                message: error.message
            });
        } else {
            res.status(500).json({
                code: STATUS_CODES.SERVER_ERROR,
                message: error.message || '点踩失败'
            });
        }
    }
});

// 获取用户评论历史
router.get('/user/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { page = 1, limit = 20 } = req.query;
        
        if (!userId) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '用户ID不能为空'
            });
        }
        
        const result = await commentsAPI.getUserComments({
            userId: parseInt(userId),
            page: parseInt(page),
            limit: parseInt(limit)
        });
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '获取用户评论历史成功',
            data: result
        });
    } catch (error) {
        console.error('获取用户评论历史失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR,
            message: error.message || '获取用户评论历史失败'
        });
    }
});

// 获取视频评论统计
router.get('/stats/:videoID', async (req, res) => {
    try {
        const { videoID } = req.params;
        
        if (!videoID) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '视频ID不能为空'
            });
        }
        
        const stats = await commentsAPI.getCommentStats(parseInt(videoID));
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '获取评论统计成功',
            data: stats
        });
    } catch (error) {
        console.error('获取评论统计失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR,
            message: error.message || '获取评论统计失败'
        });
    }
});

// 获取评论回复列表
router.get('/replies/:commentId', async (req, res) => {
    try {
        const { commentId } = req.params;
        const { page = 1, limit = 10 } = req.query;
        
        if (!commentId) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '评论ID不能为空'
            });
        }
        
        // 获取父评论信息
        const parentComment = await commentsAPI.getCommentDetail(parseInt(commentId));
        if (!parentComment) {
            return res.status(404).json({
                code: STATUS_CODES.NOT_FOUND,
                message: '父评论不存在'
            });
        }
        
        // 获取回复列表
        const result = await commentsAPI.getCommentList({
            videoID: parentComment.videoID,
            parentId: parseInt(commentId),
            page: parseInt(page),
            limit: parseInt(limit)
        });
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '获取评论回复列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取评论回复列表失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR,
            message: error.message || '获取评论回复列表失败'
        });
    }
});

module.exports = router;